class Solution {
    vector<int> ret;
    vector<int> index;
    int arrIndexs[500001];
    int arrNums[500001];

public:
    vector<int> countSmaller(vector<int>& nums) {
        int n=nums.size();
        ret.resize(n);
        index.resize(n);
        for(int i=0;i<nums.size();i++)
        {
            index[i]=i;
        }
        mergeSort(nums,0,n-1);
        return ret;
    }
    
    void mergeSort(vector<int>& nums,int left,int right)
    {
        if(left>=right) return;

        int mid=(left+right)/2;

        mergeSort(nums,left,mid);
        mergeSort(nums,mid+1,right);

        int cur1=left,cur2=mid+1,i=0;
        while(cur1<=mid&&cur2<=right)
        {
            if(nums[cur1]<=nums[cur2])
            {
            arrNums[i]=nums[cur2];
            arrIndexs[i++]=index[cur2++];
            }
            else
            { 
                ret[index[cur1]]+=right-cur2+1;
                arrNums[i]=nums[cur1];
                arrIndexs[i++]=index[cur1++];
               
            }
        }

        while(cur1<=mid)
        {
            arrNums[i]=nums[cur1];
            arrIndexs[i++]=index[cur1++];
        }
        while(cur2<=right)
        {
            arrNums[i]=nums[cur2];
            arrIndexs[i++]=index[cur2++];
        }

        for(int i=left;i<=right;i++)
        {
            nums[i]=arrNums[i-left];
            index[i]=arrIndexs[i-left];
        }

    }
};
